package com.company.project.controller.ldjsc.meeting;

import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class FFmpegAudioExtractor {

    /**
     * 从视频文件中提取音频
     * @param videoPath 视频文件路径
     * @param audioPath 输出音频文件路径
     * @throws IOException IO异常
     * @throws InterruptedException 中断异常
     */
    public static void extractAudio(String videoPath, String audioPath)
            throws IOException, InterruptedException {

        // 构建FFmpeg命令
        ProcessBuilder processBuilder = new ProcessBuilder(
                "ffmpeg",
                "-i", videoPath,
                "-vn",
                "-ar", "16000",
                "-ac", "1",
                "-f", "wav",
                audioPath
        );

        // 重定向错误流到输出流
        processBuilder.redirectErrorStream(true);

        // 启动进程
        Process process = processBuilder.start();

        // 读取输出信息
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
        );

        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        // 等待进程完成
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("FFmpeg执行失败，退出码: " + exitCode);
        }
    }

    /**
     * 检查FFmpeg是否可用
     * @return 是否可用
     */
    public static boolean isFFmpegAvailable() {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("/data/ffmpeg/ffmpeg-7.0.2-arm64-static/ffmpeg", "-version");
            Process process = processBuilder.start();
            return process.waitFor() == 0;
        } catch (Exception e) {
            return false;
        }
    }

}
